package com.sunfeng.netty.atguigu.protocoltcp2;

import com.sunfeng.netty.atguigu.protocoltcp.MessageProtocol;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author 孙峰
 * @Description: netty  数据包粘包拆包问题
 *  Sharable 表示此handler 可以被加入到多个ChannelPipeline中
 *
 * @date 2020/12/11 10:30
 */
@ChannelHandler.Sharable
public class MyServerHandler extends SimpleChannelInboundHandler<UserProtocol> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, UserProtocol msg) throws Exception {
        // 服务端读取数据并发送相关数据到刻画段

        //接收到数据，并处理
        int len = msg.getLength();
        byte[] content = msg.getContent();

        //获取数据的长度
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, StandardCharsets.UTF_8));

        System.out.println("服务器接收到消息包数量=" + (++this.count));

        //回复消息

        String responseContent = UUID.randomUUID().toString();
        int responseLen = responseContent.getBytes(StandardCharsets.UTF_8).length;
        byte[]  responseContent2 = responseContent.getBytes(StandardCharsets.UTF_8);
        //构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(responseLen);
        messageProtocol.setContent(responseContent2);

        ctx.writeAndFlush(messageProtocol);
    }
}
